package com.leyou.order.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    private static final String COOKIE_NAME = "LY_TOKEN";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //获取token
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            //解析token，获取载荷
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            //将载荷中的用户信息绑定Threadlocal
            UserInfo userInfo = payload.getUserInfo();
            UserHolder.setUser(userInfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
       //请求执行完毕后，清除Threadlocal中记录的用户信息
        UserHolder.removeUser();
    }
}
